class MyPageHeader extends BaseEditMaster {
    constructor(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
            returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl) {
        super(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
                returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl);
        this.hasFilterValue = true;
    }
    GetFilterValue() {
        return this.dataId;
    }
    // 得到角色数据
    GetEntityData() {
        let item = {};
        item['roleId'] = $("#RoleId").val();
        item['roleNo'] = $.trim($("#RoleNo").val());        // 角色编号
        item['roleName'] = $.trim($("#RoleName").val());    // 角色名称
        item['description'] = formatNullInputValue($.trim($("#Description").val()));  // 备注
        item['createdBy'] = $.trim($("#UserId").val());
        item['updatedBy'] = $.trim($("#UserId").val());

        return JSON.stringify(item);
    }
    FillData(data) {
        let item = data.RoleEntity;
        $("#RoleId").val(item.roleId);
        $("#RoleNo").val(item.roleNo);
        $("#RoleName").val(item.roleName);
        $("#Description").val(item.description);

        // 显示明细数据
        _InstancePageLines.BuildDataTable(data.UsersList);
    }
    Save() {
        super.Save(function (data, $self) {
            if (data > 0) {
                if (parseInt($self.pageStatus) === 1) {
                    $self.dataId = data;
                    $("#RoleId").val(data);   // 设置刚才插入的记录ID
                    $("#panelSlave").show();
                    $self.pageStatus = 2;
                }
            }
        });
    }
    New() {
        super.New();
        // 默认设置一些值
        $('#RoleId').val("0");
        $('#tabData01 tbody').empty();
        $("#panelSlave").hide();
        this.dataId = 0;
        this.rows = 0;
        //自适应高度
        _InstancePageLines.AutoAdjustTableHeightForLines();
        $("#RoleNo").focus();
    }
    Expand() {
        super.Expand(function () {
            // 自适应高度
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });
    }
    /* 折叠 */
    Collapse() {
        super.Collapse(function () {
            // 自适应高度
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });
    }
}

class MyPageLines extends BaseEditSlave {
    constructor() {
        super('', '', '');
    }
    BuildDataTable(result) {
        $('#tabData01 tbody').empty();
        // 得到数据列表
        if (result === null || result.length === 0) {
            this.rows = 0;
            // 自适应高度
            _InstancePageLines.AutoAdjustTableHeightForLines();
            $('#loading').hide();
            return false;
        }
        let content01 = '';
        this.rows = result.length;
        this.numCheckbox = result.length;
        for (var i = 0; i < result.length; i++) {
            content01 += '<tr _mash_id="' + result[i].employeeId + '">';
            content01 += '<td style="padding-left:6px;"><label class="btn" for="R-' + result[i].employeeId + '"><input id="R-' + result[i].employeeId + '" name="_check_row" type="checkbox" onclick="_InstancePageLines.DoCheckRow($(this),\'_check_row\', $(\'#CheckAll\'));" value="' + result[i].employeeId + '"/><i></i><span></span></label></td>';
            // 删除权限判断
            if ($("#ActionAcl_4").length === 0 || parseInt($("#ActionAcl_4").val() === 0)) {
                content01 += '<td></td>';
            } else {
                content01 += '<td class="column__action"><span title="删除" class="trash" onclick="_InstancePageLines.DeleteLines($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
            }
            content01 += '<td>' + formatNullData(result[i].employeeName) + '</td>';
            if (i > 0) {
                if (result[i].departmentName === result[i - 1].departmentName) {
                    content01 += '<td style="border-bottom:none;"></td>';
                } else {
                    content01 += '<td style="border-top:1px solid #c6c3bd; border-bottom:none;">' + formatNullData(result[i].departmentName) + '</td>';
                }
            } else {
                content01 += '<td style="border-bottom:none;">' + formatNullData(result[i].departmentName) + '</td>';
            }
            content01 += '</tr>';

            $('#tabData01 tbody').append(content01);
            content01 = '';
        }
        setOneTableRowColor("tabData01");

        // 设置明细部分高度
        this.AutoAdjustTableHeightForLines();
        $('#loading').hide();
    }
    DeleteLines($self) {
        let params = {};
        params['employeeId'] = $self.parent().parent().attr("_mash_id");
        params['employeeName'] = $self.parent().parent().find("td").eq(2).text();
        params['roleId'] = $("#RoleId").val();
        params['roleName'] = $("#RoleName").val();
        params['deletedBy'] = $("#UserId").val();
        super.DeleteLines(params, "/workflow/task_role/lines/delete.html", function (data, _this) {
            if (data.LinesList !== undefined) {
                // 刷新明细
                _this.BuildDataTable(data.LinesList);
            }
            ShowSuccessMessagePanel('删除成功。');
        });
    }
    // 批量删除
    BatchDeleteLines() {
        if ($("input[type='checkbox'][name='_check_row']:checked").length <= 0) {
            ShowErrorMessagePanel("请先选择要删除的数据。");
            return false;
        }
        showModal(350, 140, '确认删除', '', null, null, 1, '请问，确定要删除所选数据吗？', () => {
            super.DoAjax(this.GetCheckedLinesData(), "/workflow/task_role/lines/batch_delete.html", function (data, $self) {
                $self.BuildDataTable(data.LinesList);
                $("#CheckAll").prop("checked", false);
                ShowSuccessMessagePanel('删除成功。');
            });
        });
    }
    // 得到选择的数据
    GetCheckedLinesData() {
        let _result = [];
        $('#tabData01 tbody').find("tr").each(function () {
            if ($(this).children("td").eq(0).children("label").eq(0).children("input[type='checkbox'][name='_check_row']").is(":checked") === true) {
                let instance = {};
                instance['employeeId'] = $(this).attr("_mash_id");
                instance['roleId'] = $("#RoleId").val();
                instance['employeeName'] = $.trim($(this).find("td").eq(2).text());
                instance['roleName'] = $("#RoleName").val();
                instance['updatedBy'] = $.trim($("#UserId").val());
                instance['deletedBy'] = $.trim($("#UserId").val());
                _result.push(instance);
            }
        });
        return _result;
    }
    NewLines() {
        let _choice = new CommonChoice();
        _choice.DoChoiceUser(1, '选择系统用户', null, (data) => {
            if (data) {
                let _result = [];
                for (let i = 0; i < data.length; i++) {
                    let item = {};
                    item['employeeId'] = parent.arrChoice[0][i].EmployeeId;
                    item['employeeName'] = parent.arrChoice[0][i].EmployeeName;
                    item['roleId'] = parseInt($("#RoleId").val());
                    item['roleName'] = $("#RoleName").val();
                    item['createdBy'] = parseInt($.trim($("#UserId").val()));
                    item['updatedBy'] = parseInt($.trim($("#UserId").val()));

                    _result.push(item);
                }
                // 保存，根据所选，增加明细表记录
                super.DoAjax(_result, "/workflow/task_role/lines/insert.html", function (data, _this) {
                    _this.BuildDataTable(data.LinesList);
                    ShowSuccessMessagePanel("角色用户增加成功。");
                });
            }
        });
    }
    // 设置行选择后的状态
    SetRowStatus($self) {
        super.AdjustRowStatus($self, function ($row, index) {
            // 设置删除按钮失效
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", "");
        }, function ($row, index) {
            // 设置删除按钮有效
            let _event_delete_onclick = '_InstancePageLines.DeleteLines($(this))';
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", _event_delete_onclick);
        });
    }
    AutoAdjustTableHeightForLines() {
        let h = $(window).height();
        let _tabTop = $("#divD1").offset().top;   // 用于随着窗口变化，下面明细高度随之变化的一个节点
        let _rc = Math.floor((h - _tabTop) / 25);
        let _dh = _rc * 25;
        let _rowH = this.rows * 25; // 计算行高
        _dh = (_rowH >= _dh) ? _dh : _rowH;

        $("#divD1").css({"max-height": _dh, height: _dh});
    }
}

var _InstancePageHeader = null;
var _InstancePageLines = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    let _pageStatus = parseInt($("#Action").val());
    let _dataId = $("#RoleId").val();

    let task_role_list_result = $.cookie("task_role_list_result") === undefined ? "" : $.cookie("task_role_list_result");
    let _pageListData = [];
    if (task_role_list_result !== "") {
        _pageListData = task_role_list_result.split(',');
        $("#rec_total_rows").text(_pageListData.length);
        $("#rec_cur_row").text($.inArray(_dataId, _pageListData) + 1);

        if (_pageListData.length > 0) {
            let index = $.inArray(_dataId, _pageListData);
            if (index === 0) {
                $("#ButPrev").attr("disabled", "disabled");
            } else {
                $("#ButNext").removeAttr("disabled");
            }
            if (index === (_pageListData.length - 1)) {
                $("#ButNext").attr("disabled", "disabled");
            } else {
                $("#ButPrev").removeAttr("disabled");
            }
        }
    } else {
        $("#rec_total_rows").text("1");
        $("#rec_cur_row").text("1");
    }

    _InstancePageHeader = new MyPageHeader(_dataId, 0, 0, _pageStatus, _pageListData,
            "/workflow/task_role/list.html",
            "/workflow/task_role/fetchByKey.html",
            "/workflow/task_role/save.html",
            null, null);

    _InstancePageLines = new MyPageLines();

    $("#tabPanelHeader").wxTabs({tabContent: "tabPanelContent"});

    $("#hPanelSplitter").click(function () {
        if ($(this).children("i").hasClass("fa-angle-double-up")) {
            _InstancePageHeader.Collapse();
        } else {
            _InstancePageHeader.Expand();
        }
    });

    _InstancePageHeader.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    if (_InstancePageLines !== null)
        _InstancePageLines.AutoAdjustTableHeightForLines();
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
$.validator.setDefaults({
    ignore: 'hidden, [reaonly=readonly]'
});
$(function () {
    $("#form_data").validate({
        // Step 1：设置验证规则和错误消息
        rules: {
            _RoleNo: "required",
            _RoleName: "required"
        },
        messages: {
            _RoleNo: "请填写角色编号。",
            _RoleName: "请填写角色名称。"

        },
        // Step 2：设置验证触发事件
        onclick: false,
        onfocusout: false,
        onfocusin: false,
        onkeyup: false,
        onkeydown: false,
        focusInvalid: false,
        // Step 3：设置错误信息提示
        showErrors: window.showErrors  //使用自定义的错误显示方法
    });
});